package com.tanqidi.arcgisandroid.ui.projectConfig

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.switchmaterial.SwitchMaterial
import com.tanqidi.arcgisandroid.R
import com.tanqidi.arcgisandroid.base.BaseRecyclerAdapter
import com.tanqidi.arcgisandroid.base.RecyclerViewHolder
import com.tanqidi.arcgisandroid.base.utils.*
import com.tanqidi.arcgisandroid.data.project.Project
import com.tanqidi.arcgisandroid.databinding.FragmentProjectConfigBinding
import com.tanqidi.arcgisandroid.databinding.ItemDialogInputBinding
import com.tanqidi.arcgisandroid.ui.HomeViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class ProjectConfigFragment : Fragment() {

    private lateinit var binding: FragmentProjectConfigBinding
    private val projectConfigViewModel by viewModels<ProjectConfigViewModel>()
    private lateinit var adapter: ProjectAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentProjectConfigBinding.inflate(layoutInflater)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        initTopBar()
        initViewEvent()
        initLiveData()
        initRecycleView()
        return binding.root
    }

    private fun initRecycleView() {
        val recyclerView = binding.recyclerView
        adapter = ProjectAdapter(requireContext(), null)
        adapter.setOnItemClickListener { itemView, pos ->
            val item = adapter.getItem(pos)
            val action = ProjectConfigFragmentDirections.actionProjectConfigFragmentToLayerConfigFragment(item.name)
            findNavController().navigate(action)
        }
        recyclerView.adapter = adapter

        projectConfigViewModel.listProject()
    }

    private fun initViewEvent() {
        binding.addFloatingActionButton.setOnClickListener {
            val dialogBinding = ItemDialogInputBinding.inflate(layoutInflater)
            val dialog = MaterialAlertDialogBuilder(requireContext())
                .setTitle("新建项目")
                .setView(dialogBinding.root)
                .show()

            dialogBinding.apply {
                accept.setOnClickListener {
                    val content = textInputEditText.text.toString().trim()
                    if(TextUtils.isEmpty(content)){
                        textInputLayout.error = "内容不可为空"
                    } else {
                        //保存配置文件到配置目录
                        projectConfigViewModel.saveProject(Project().apply { name = content })
                        showToast("创建成功")
                        projectConfigViewModel.listProject()
                        dialog.dismiss()
                    }
                }
            }
        }
    }

    private fun initLiveData() {
        //数据推送
        projectConfigViewModel.listProjectLiveData.observe(viewLifecycleOwner) {
            adapter.data = it
        }
    }

    private fun initTopBar() {
        binding.topAppBar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }
    }

    private inner class ProjectAdapter(context: Context, list:List<Project>?) : BaseRecyclerAdapter<Project>(context, list) {
        override fun getItemLayoutId(viewType: Int): Int {
            return R.layout.rv_item_project
        }
        override fun bindData(holder: RecyclerViewHolder, position: Int, item: Project) {
            val instance = SPUtils.getInstance()
            holder.getTextView(R.id.title).text = item.name
            holder.getView(R.id.setting).setOnClickListener {
                showMenu(it, R.menu.project_menu) {
                    when(it.itemId){
                        R.id.export -> {
                            val action = ProjectConfigFragmentDirections.actionProjectConfigFragmentToExportDataFragment(item.name)
                            findNavController().navigate(action)
                        }
                        R.id.create_shp -> {
                            showConfirmDialog(requireContext(), "提示", "确定生成shp吗") { dialog, which ->
                                projectConfigViewModel.createShp(item)
//                                showToast("创建成功")  成功与否是在里面提示的
                            }
                        }
                        R.id.create_geodatabase -> {
                            showConfirmDialog(requireContext(), "提示", "确定生成geodatabase吗") { dialog, which ->
                                projectConfigViewModel.createGeodatabase(item)
//                                showToast("创建成功")  成功与否是在里面提示的
                            }
                        }
                        R.id.delete_project -> {
                            //不能删除主项目配置
                            val mainProject = getSPUtils().getString(getString(R.string.main_project))
                            if(mainProject != item.name){
                                showConfirmDialog(requireContext(), "提示", "确定删除项目吗") { dialog, which ->
                                    projectConfigViewModel.deleteProject(item)
                                    remove(holder.absoluteAdapterPosition)
                                }
                            } else {
                                showToast("不可删除主项目配置")
                            }

                        }
                    }
                    true
                }
            }
            (holder.getView(R.id.switchMaterial) as SwitchMaterial).apply {
                isChecked = instance.getString(getString(R.string.main_project), "") == item.name
                setOnClickListener {
                    if(isChecked){
                        instance.put(getString(R.string.main_project), item.name)
                    } else {
                        instance.remove(getString(R.string.main_project))
                    }
                    notifyDataSetChanged()
                }
            }
        }

    }
}